package com.tbit.uqbike.client.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.tbit.common.constant.*;
import com.tbit.common.entity.BalanceChange;
import com.tbit.common.entity.UserAccountMoney;
import com.tbit.uqbike.client.constant.RechargeConstant;
import com.tbit.uqbike.client.constant.RefundConstant;
import com.tbit.uqbike.client.dao.capital.AdaPayLogDao;
import com.tbit.uqbike.client.dao.capital.RideFeeLogDao;
import com.tbit.uqbike.client.dao.capital.TransationLogDao;
import com.tbit.uqbike.client.dao.core.*;
import com.tbit.uqbike.client.dao.log.*;
import com.tbit.uqbike.client.exception.BaseException;
import com.tbit.uqbike.client.pojo.*;
import com.tbit.uqbike.client.pojo.newEntity.*;
import com.tbit.uqbike.client.remote.sms.ClzySmsAuthUtil;
import com.tbit.uqbike.client.remote.sms.apistore.ApiStoreMsgUtils;
import com.tbit.uqbike.client.service.*;
import com.tbit.uqbike.client.util.DoubleUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 退款日志记录
 *
 * @author <a href="mailto:zhang.zhiliang@tbit.com.cn">Zhang ZhiLiang</a>
 * @version 1.0
 * @see <a href="http://adsl1.tbit.com.cn:21490/pages/viewpage.action?pageId=82182491">订单号规范</a>
 * @since 2024/6/16
 */
@Slf4j
@Service
public class RefundDoLogServiceImpl implements RefundDoLogService{

    @Autowired
    private RechargeService rechargeService;
    @Autowired
    private WeixinPayService weixinPayService;
    @Autowired
    private UserDao userDao;
    @Autowired
    private AdaPayService adaPayService;
    @Autowired
    private RefundOrderDao refundOrderDao;
    @Autowired
    private MemberFeeDao memberFeeDao;
    @Autowired
    private AgentDepositVipDao agentDepositVipDao;
    @Autowired
    private RideCardDao rideCardDao;
    @Autowired
    private VipCardDao vipCardDao;
    @Autowired
    private UserMealLogDao userMealLogDao;
    @Autowired
    private CouponMealDao couponMealDao;
    @Autowired
    private CouponDao couponDao;
    @Autowired
    private RideFeeLogDao rideFeeLogDao;
    @Autowired
    private UserService userService;
    @Autowired
    private RideRefundLogDao rideRefundLogDao;
    @Autowired
    private RefundOpeLogDao refundOpeLogDao;
    @Autowired
    private AccountDao accountDao;
    @Autowired
    private SmsAuthConfigDao smsAuthConfigDao;
    @Autowired
    private UserMsgDao usermsgDao;
    @Autowired
    private RideUseLogService rideUseLogService;
    @Autowired
    private RideUseRefundLogDao rideUseRefundLogDao;
    @Autowired
    private AdaPayLogService adaPayLogService;
    @Autowired
    private UserAdaPayLogService userAdaPayLogService;
    @Autowired
    private RideLogService rideLogService;
    @Autowired
    private UserAdaPayMoneyService userAdaPayMoneyService;
    @Autowired
    private PushMsgLogService pushMsgLogService;
    @Autowired
    private UserAccountLogService userAccountLogService;
    @Autowired
    private UserAccountMoneyService userAccountMoneyService;
    @Autowired
    private UserAccountMoneyDao userAccountMoneyDao;
    @Autowired
    private GiftCardUserService giftCardUserService;
    @Autowired
    private RefundAdapayRecordDao refundAdapayRecordDao;
    @Autowired
    private AccountService accountService;


    /**
     * 退款日志记录
     * 根据退款同步调用的结果，对refundorder打上对应的标记，根据对应的标记进行记录
     * @param logTag
     */
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRES_NEW)
    public void dealLog(String logTag, String refundNo, DateTime time, ZfbPayConfig zfbPayConfig,
                         AdaPayConfig adaPayConfig, WeixinPayConfig weixinPayConfig, Message message) {
        if (Objects.isNull(logTag)){
            log.error("logTag该数据不可能为空！！！");
            return;
        }
        RefundOrder refundOrder = refundOrderDao.getByRefundNO(refundNo);
        if (Objects.isNull(refundOrder)){
            log.error("refundorder为空，请排查refundorder插入问题,refundNO={}",refundNo);
            return ;
        }
        String[] tags = logTag.split(",");
        for (String tag : tags) {
            if (Objects.equals(RefundConstant.LOG1,tag)){
                log1(refundNo,time);
            }
            if (Objects.equals(RefundConstant.LOG2,tag)){
                log2(refundNo,time);
            }
            if (Objects.equals(RefundConstant.LOG3,tag)){
                log3(weixinPayConfig,time,refundNo);
            }
            if (Objects.equals(RefundConstant.LOG4,tag)){
                log4(zfbPayConfig,time,refundNo);
            }
            if (Objects.equals(RefundConstant.LOG5,tag)){
                log5(zfbPayConfig,time,refundNo);
            }
            if (Objects.equals(RefundConstant.LOG6,tag)){
                log6(refundNo,adaPayConfig,time);
            }
            if (Objects.equals(RefundConstant.LOG7,tag)){
                log7(refundNo,time);
            }
            if (Objects.equals(RefundConstant.LOG8,tag)){
                log8(refundNo,time);
            }
            if (Objects.equals(RefundConstant.LOG9,tag)){
                log9(refundNo,adaPayConfig,time);
            }
            if (Objects.equals(RefundConstant.APILOG1,tag)){
                apiLog1(time,refundNo,message);
            }if (Objects.equals(RefundConstant.APILOG2,tag)){
                apiLog2(refundNo,time);
            }if (Objects.equals(RefundConstant.APILOG3,tag)){
                apiLog3(refundNo,time);
            }if (Objects.equals(RefundConstant.APILOG4,tag)){
                apiLog4(refundNo);
            }   
        }
    }

    /**
     * 每一笔退款订单对应的数据库记录 函数
     *
     * @param refundNO         退款订单号
     */
    private void log1(String refundNO,DateTime time) {
        log.info("参数refundNO={}",refundNO);
        RefundOrder refundOrder = refundOrderDao.getByRefundNO(refundNO);
        Integer userId = refundOrder.getUserId();
        // 记录退款的订单编号
        User beforeUser = userDao.getByUserId(userId);
        Long beforeUserMoney = beforeUser.getMoney().longValue();
        Double refundMoney = refundOrder.getRefundMoney();
        // 操作数据库 跟新用户可用余额
        userService.updateMoney(userId, -refundMoney);

        String orderNO = refundOrder.getRechargeNO();
        Recharge recharge = rechargeService.getByOrderNO(orderNO);
        User user = userDao.getByUserId(userId);

        /**更改用户金额归属,汇付支付的独立计算，其他的全部算一类*/
        /** 充值订单支付平台为汇通天下微信小程序/支付宝小程序 */
        if (recharge.getType().equals(RechargeConstant.RECHARGE_PAY_ADAPAY) || recharge
                .getType()
                .equals(RechargeConstant.RECHARGE_PAY_ADAPAY_ZFB)) {
            // 数据库 维护用户余额表
            userAdaPayMoneyService.add(user, 0, -refundMoney.intValue());
        } else {
            // 数据库 维护用户余额表
            userAdaPayMoneyService.add(user, -refundMoney.intValue(), 0);
        }
        Integer areaId = refundOrder.getAdAccountId();
        Account account = accountService.getByAccountId(areaId);
        log.info("生成退款日志account={},user={},beforeUserMoney={},refundMoney={}", account, user, beforeUserMoney, refundMoney);
        String businessNO = refundOrder.getBusinessNO();
        /**余额变动日志*/
        BalanceChange balanceChange = new BalanceChange(user.getUserId(), user.getPhone(), user.getName()
                , account == null ? -1 : account.getAccountId(), user.getAccountId(), beforeUserMoney, refundMoney.longValue()
                , beforeUserMoney - refundMoney.longValue(), IncomeTypeContent.inComeRefund,
                BalanceLogChangeTypeContent.capitalType_balance, BalanceLogCapitalTypeContent.USER_REFUNDED_BALANCE
                , System.currentTimeMillis(), null, businessNO);
        log.info("推送退款消息");
        // 推送MQ消息 余额变动日志
        pushMsgLogService.sendPushLog(JSON.toJSONString(balanceChange), TableNameConstant.BALANCECHANGE);
        /**记录退款日志*/
        UserAccountLog userAccountLog = new UserAccountLog();
        userAccountLog.setMoneyType(RechargeConstant.MONEY_TYPE_REAL);
        userAccountLog.setAccountId(user.getAccountId());
        userAccountLog.setMoney(refundMoney);
        userAccountLog.setUserId(userId);
        String s = DateUtil.formatDateTime(time);
        userAccountLog.setOperaTime(s);
        userAccountLog.setRemark("正常退款");
        userAccountLog.setType(0);
        userAccountLogService.insert(userAccountLog);
        adaPayService.addRefundLog(recharge, areaId, refundNO, refundMoney, userId, recharge.getOrderNO());
    }


    /**
     * 一个区域的充值订单退款汇总
     */
    private void log2(String refundNO, DateTime time) {
        log.info("参数refundNO={}",refundNO);
        String remark = null;
        // 退款情况下 OrderNo 存 退款订单号
        RefundOrder refundOrder = refundOrderDao.getByRefundNO(refundNO);
        Integer areaId = refundOrder.getAdAccountId();
        Integer userId = refundOrder.getUserId();
        User user = userDao.getByUserId(userId);
        Account account = accountDao.getByAccountId(areaId);
        String rechargeNO = refundOrder.getRechargeNO();
        Recharge recharge = rechargeService.getByOrderNO(rechargeNO);
        // 业务订单号
        String businessNO = refundOrder.getBusinessNO();

        Double areaAlreadyRefundMoney = refundOrder.getAreaAlreadyRefundMoney();

        String merchantNOListStr = refundOrder.getMerchantNOListStr();
        List<String> merchantNOList = JSON.parseArray(merchantNOListStr, String.class);

        adaPayService.pushRefundLog(user, account, areaAlreadyRefundMoney, businessNO, merchantNOList, null,
                RefundLogContent.balance_Refund, null, refundOrder.getOperatorId(), refundOrder.getOperatorName(), refundOrder.getOperatorPhone(), null,time);

        /**清除区域金额*/
        UserAccountMoney giftCardMoney = userAccountMoneyService.getByAccountId(user.getUserId(), BalanceLogChangeTypeContent.capitalType_giftCard, areaId);
        UserAccountMoney balanceMoney = userAccountMoneyService.getByAccountId(user.getUserId(), BalanceLogChangeTypeContent.capitalType_balance, areaId);
        /**清除礼品卡余额*/
        if (giftCardMoney != null) {
            long giftCardStartMoney = giftCardMoney.getMoney();
            if (giftCardStartMoney > 0) {
//							giftCardMoney.setMoney(-giftCardMoney.getMoney());
//							userAccountMoneyDao.edit(giftCardMoney);
//							BalanceChange giftCardBalanceChange = new BalanceChange(user.getUserId(),user.getPhone(), user.getName()
//									,account.getAccountId(), user.getAccountId(), giftCardStartMoney, giftCardStartMoney
//									,0L, IncomeTypeContent.inComeRefund,
//									BalanceLogChangeTypeContent.capitalType_giftCard, BalanceLogCapitalTypeContent.REFUND_BALANCE_MINUS_GIFT_CARD
//									, now.getTime(), "余额退款清除礼品卡余额",businessNO);
//							pushMsgLogService.sendPushLog(JSON.toJSONString(giftCardBalanceChange), TableNameConstant.BALANCECHANGE);
//							UserToAgent userToAgent = userToAgentDao.getByUserId(user.getUserId());
//							Integer originalAccountId = null;
//							if(userToAgent != null){
//								originalAccountId = userToAgent.getFirstId();
//							}
//							UserCapitalChange userCapitalChange =new UserCapitalChange(user.getUserId(),user.getPhone(),
//									user.getName(),account.getAccountId(),user.getAccountId(),giftCardStartMoney,giftCardStartMoney,
//									0L,PayPlatformContent.PAY_USE,PayPlatformContent.PAY_GIFCARD,BusinessConstant.BUSINESS_DEDUCTION_GIF
//									,null,operatorId,operatorPhone,operatorName,businessNO,null,now.getTime(),
//									"余额退款清除礼品卡余额", originalAccountId);
//							pushMsgLogService.sendPushLog(JSON.toJSONString(userCapitalChange), TableNameConstant.USERCAPITALCHANGE);
            }
        }


        Double needRefundMoney = areaAlreadyRefundMoney;
        //清除预存款
        if (balanceMoney != null) {
            if (needRefundMoney >= balanceMoney.getMoney()) {   // 需要退款金额大于用户余额
                needRefundMoney = needRefundMoney - balanceMoney.getMoney();
                balanceMoney.setMoney(-balanceMoney.getMoney());
                userAccountMoneyDao.edit(balanceMoney); // 加上其自身的负数，等于归0
            } else {
                balanceMoney.setMoney(-needRefundMoney.longValue());
                needRefundMoney = 0D;   // 需退款金额全部从余额中拿了
                userAccountMoneyDao.edit(balanceMoney);
            }
        }
        // 余额不够退款的情况
        if (needRefundMoney > 0) {
            // 跨运营区域金额还款
            List<UserAccountMoney> userAccountMonies = userAccountMoneyService.getByUserIdAndBrandId(userId, BalanceLogChangeTypeContent.capitalType_balance);
            for (UserAccountMoney userAccountMoney : userAccountMonies) {
                if (userAccountMoney.getMoney() == 0) {
                    continue;
                }
                if (needRefundMoney > userAccountMoney.getMoney()) {
                    needRefundMoney = needRefundMoney - userAccountMoney.getMoney();
                    userAccountMoney.setMoney(-userAccountMoney.getMoney());
                    userAccountMoneyDao.edit(userAccountMoney);
                } else {
                    userAccountMoney.setMoney(-needRefundMoney.longValue());
                    userAccountMoneyDao.edit(userAccountMoney);
                    break;
                }
            }
        }

        // 清理礼品卡余额
        // 查询用户是否存在礼品卡余额
        GiftCardUser giftCardUser = giftCardUserService.getByUserId(user.getUserId(), areaId);
        log.info("退款查询礼品卡信息：userId=" + user.getUserId() + ",adAccountId=" + areaId);
        if (giftCardUser != null && giftCardUser.getMoney() > 0) {
            long giftCardStartMoney = giftCardUser.getMoney();
            giftCardUser.setMoney(-giftCardUser.getMoney());
            giftCardUser.setUpdateTime(time.toString());
            giftCardUserService.insert(giftCardUser, "余额退款清除礼品卡余额",
                    BalanceLogCapitalTypeContent.REFUND_BALANCE_MINUS_GIFT_CARD, businessNO, time.toString());
            log.info("退款清除礼品卡余额=" + giftCardStartMoney);
        }
    }

    private void log3(WeixinPayConfig weixinPayConfig, DateTime time, String refundNO){
        log.info("参数refundNO={}",refundNO);
        RefundOrder refundOrder = refundOrderDao.getByRefundNO(refundNO);
        String rideOrderNo = refundOrder.getRideOrderNO();
        Recharge recharge = rechargeService.getByOrderNO(refundOrder.getRechargeNO());
        Double refundMoney = refundOrder.getRefundMoney();
        User user = userService.getByUserId(refundOrder.getUserId());
        Account account = accountService.getByAccountId(refundOrder.getAdAccountId());
        addRideUseLog(rideOrderNo, recharge, refundMoney, weixinPayConfig.getPartner(),time.toString());
//        weixinPayService.sendPayMsg(refundNO, RechargeConstant.PAY_REFUND);
        //  退款时间
        String refundBusinessNO = refundOrder.getBusinessNO();
        Integer operatorId = refundOrder.getOperatorId();
        String operatorName = refundOrder.getOperatorName();
        String operatorPhone = refundOrder.getOperatorPhone();
        String transactionLogRemark = refundOrder.getTransactionLogRemark();

        adaPayService.pushRefundDetailLog(user, account, refundMoney, refundNO, refundBusinessNO, recharge, operatorId, operatorName, operatorPhone, null, rideOrderNo, transactionLogRemark,time);
        log.info("订单号=" + recharge.getOrderNO() + ",退款金额=" + refundMoney + "退款结果=" + true);
    }

    private void log4(ZfbPayConfig zfbPayConfig, DateTime time, String refundNO){
        log.info("参数refundNO={}",refundNO);
        RefundOrder refundOrder = refundOrderDao.getByRefundNO(refundNO);
        String rideOrderNo = refundOrder.getRideOrderNO();
        Recharge recharge = rechargeService.getByOrderNO(refundOrder.getRechargeNO());
        Double refundMoney = refundOrder.getRefundMoney();
        User user = userService.getByUserId(refundOrder.getUserId());
        Account account = accountService.getByAccountId(refundOrder.getAdAccountId());
        addRideUseLog(rideOrderNo, recharge, refundMoney, zfbPayConfig.getPartner(),time.toString());
//        weixinPayService.sendPayMsg(refundNO, RechargeConstant.PAY_REFUND);
        //  退款时间
        String refundBusinessNO = refundOrder.getBusinessNO();
        Integer operatorId = refundOrder.getOperatorId();
        String operatorName = refundOrder.getOperatorName();
        String operatorPhone = refundOrder.getOperatorPhone();
        String transactionLogRemark = refundOrder.getTransactionLogRemark();

        adaPayService.pushRefundDetailLog(user, account, refundMoney, refundNO, refundBusinessNO, recharge, operatorId, operatorName, operatorPhone, null, rideOrderNo, transactionLogRemark,time);
        log.info("订单号=" + recharge.getOrderNO() + ",退款金额=" + refundMoney + "退款结果=" + true);
    }

    private void log5(ZfbPayConfig zfbPayConfig, DateTime time, String refundNO){
        log.info("参数refundNO={}",refundNO);
        RefundOrder refundOrder = refundOrderDao.getByRefundNO(refundNO);
        String rideOrderNo = refundOrder.getRideOrderNO();
        Recharge recharge = rechargeService.getByOrderNO(refundOrder.getRechargeNO());
        Double refundMoney = refundOrder.getRefundMoney();
        User user = userService.getByUserId(refundOrder.getUserId());
        Account account = accountService.getByAccountId(refundOrder.getAdAccountId());
        addRideUseLog(rideOrderNo, recharge, refundMoney, zfbPayConfig.getPartner(),time.toString());
//        weixinPayService.sendPayMsg(refundNO, RechargeConstant.PAY_REFUND);
        //  退款时间
        String refundBusinessNO = refundOrder.getBusinessNO();
        Integer operatorId = refundOrder.getOperatorId();
        String operatorName = refundOrder.getOperatorName();
        String operatorPhone = refundOrder.getOperatorPhone();
        String transactionLogRemark = refundOrder.getTransactionLogRemark();

        adaPayService.pushRefundDetailLog(user, account, refundMoney, refundNO, refundBusinessNO, recharge, operatorId, operatorName, operatorPhone, null, rideOrderNo, transactionLogRemark,time);
        log.info("订单号=" + recharge.getOrderNO() + ",退款金额=" + refundMoney + "退款结果=" + true);
    }

    private void log6(String refundNO, AdaPayConfig adaPayConfig, DateTime time){
        log.info("参数refundNO={}",refundNO);
        RefundOrder refundOrder = refundOrderDao.getByRefundNO(refundNO);
        String rideOrderNo = refundOrder.getRideOrderNO();
        Recharge recharge = rechargeService.getByOrderNO(refundOrder.getRechargeNO());
        Double refundMoney = refundOrder.getRefundMoney();
        addRideUseLog(rideOrderNo, recharge, refundMoney, adaPayConfig.getAppId(),time.toString());
    }

    private void log7(String refundNO, DateTime time){
        log.info("参数refundNO={}",refundNO);
        RefundOrder refundOrder = refundOrderDao.getByRefundNO(refundNO);
        String rideOrderNo = refundOrder.getRideOrderNO();
        Recharge recharge = rechargeService.getByOrderNO(refundOrder.getRechargeNO());
        Double refundMoney = refundOrder.getRefundMoney();
        User user = userService.getByUserId(refundOrder.getUserId());
        Account account = accountService.getByAccountId(refundOrder.getAdAccountId());

//        weixinPayService.sendPayMsg(refundNO, RechargeConstant.PAY_REFUND);
        String refundBusinessNO = refundOrder.getBusinessNO();
        Integer operatorId = refundOrder.getOperatorId();
        String operatorName = refundOrder.getOperatorName();
        String operatorPhone = refundOrder.getOperatorPhone();
        String transactionLogRemark = refundOrder.getTransactionLogRemark();

        adaPayService.pushRefundDetailLog(user, account, refundMoney, refundNO, refundBusinessNO, recharge, operatorId, operatorName, operatorPhone, null, rideOrderNo, transactionLogRemark,time);
        log.info("订单号=" + recharge.getOrderNO() + ",退款金额=" + refundMoney + "退款结果=" + true);
    }

    private void log8(String refundNO, DateTime time){
        log.info("参数refundNO={}",refundNO);
        RefundOrder refundOrder = refundOrderDao.getByRefundNO(refundNO);
        String rideOrderNo = refundOrder.getRideOrderNO();
        Recharge recharge = rechargeService.getByOrderNO(refundOrder.getRechargeNO());
        Double refundMoney = refundOrder.getRefundMoney();
        User user = userService.getByUserId(refundOrder.getUserId());
        Account account = accountService.getByAccountId(refundOrder.getAdAccountId());

        userAdaPayMoneyService.add(user, 0, -refundMoney.intValue());
//        weixinPayService.sendPayMsg(refundNO, RechargeConstant.PAY_REFUND);
        String refundBusinessNO = refundOrder.getBusinessNO();
        Integer operatorId = refundOrder.getOperatorId();
        String operatorName = refundOrder.getOperatorName();
        String operatorPhone = refundOrder.getOperatorPhone();
        String transactionLogRemark = refundOrder.getTransactionLogRemark();

        adaPayService.pushRefundDetailLog(user, account, refundMoney, refundNO, refundBusinessNO, recharge, operatorId, operatorName, operatorPhone, null, rideOrderNo, transactionLogRemark,time);
    }

    private void log9(String refundNO, AdaPayConfig adaPayConfig, DateTime time){
        log.info("参数refundNO={}",refundNO);
        RefundOrder refundOrder = refundOrderDao.getByRefundNO(refundNO);

        String fee_amt = refundOrder.getFeeAmt();
        log.info("获取的fee_amt={}",fee_amt);


        String buyOrderNO = refundOrder.getBusinessNO();
        List<UserAdaPayLog> userAdaPayLogs = null;
        // 判断是否余额充值订单
        Recharge recharge = rechargeService.getByOrderNO(refundOrder.getRechargeNO());
        log.info("9-充值订单{}",JSON.toJSONString(recharge));
//        // 识别余额充值订单
//        if (Objects.equals(recharge.getRechargeType(),0) && !recharge.getDeposit()){
//            userAdaPayLogs = userAdaPayLogService.getBuBuyOrderNO(recharge.getOrderNO());
//        }else {
//            userAdaPayLogs = userAdaPayLogService.getBuBuyOrderNO(buyOrderNO);
//        }
//        //todo 延时分账没问题
//        userAdaPayLogs = userAdaPayLogService.getBuBuyOrderNO(buyOrderNO);
        userAdaPayLogs = JSON.parseArray(refundOrder.getUserAdapaylogs(), UserAdaPayLog.class);

        String feeUserNO = null;
        String mainUserNO = null;
        for (UserAdaPayLog u : userAdaPayLogs) {
            if (u.getType() == 1) {
                feeUserNO = u.getUserNO();
            }
            if (u.getFee() > 0) {
                mainUserNO = u.getUserNO();
            }
        }

        Double refundServiceFee = 0D;
        log.info(String.format("支付分账对象%s", userAdaPayLogs));
        Double refundMoney = refundOrder.getRefundMoney();
        log.info("操作userRefundLog，adaPayLog，userAdaPayMoney参数refundMoney={},refundNO={},rechargeNO={}", refundMoney, refundNO, recharge.getOrderNO());
//                            adaPayService.editRefund(adaPayLog, refundMoney, refundNO, user, true, recharge.getOrderNO());

        /** 生成 支付确认对象id - 分账对象列表 */
        Double money = refundOrder.getTotalRefundMoney();
        Map<String, List<DivMembers>> map = adaPayService.getRefundDivMember(userAdaPayLogs, money, adaPayConfig.getAccountId());
        // 支付确认对象id
        String key = refundOrder.getConfirmId();
        List<DivMembers> divMembers = map.get(key);

        double feeMoney = 0D;
        for (DivMembers members : divMembers) {
            feeMoney = feeMoney + DoubleUtil.parseDouble(Double.parseDouble(members.getAmount()) * 100);
            /**用户分账日志记录金额为元，充值记录单位为分，需要兼容*/
            if (members.getMember_id().equals(feeUserNO)) {
                refundServiceFee = DoubleUtil.parseDouble(Double.parseDouble(members.getAmount()) * 100);
            }
        }
        boolean isReduce = refundOrder.getReduce();
        User user = userService.getByUserId(refundOrder.getUserId());
        //  退款时间
        AdaPayLog adaPayLog = adaPayLogService.getByConfirmId(key);
        log.info("操作adapaylog参数：adaPaylog={},feeMoney={},refundNO={},user={},isReduce={},rechargeNO={}",JSON.toJSONString(adaPayLog),feeMoney,refundNO,JSON.toJSONString(user),isReduce,recharge.getOrderNO());
        adaPayService.editRefund(adaPayLog, feeMoney, refundNO, user, isReduce, refundOrder.getRemark());
        String rideOrderNo = refundOrder.getRideOrderNO();
        adaPayService.editUserAdaPayLog(divMembers, adaPayLog.getAdaPayId(), (int) feeMoney,
                DoubleUtil.parseDouble(Double.parseDouble(fee_amt) * 100).intValue(),
                (refundServiceFee).intValue(), mainUserNO, isReduce ? null : rideOrderNo,time);
        //添加分账退款日志
        adaPayService.addAdaPayRefundLog(userAdaPayLogs, divMembers, refundNO, (int) feeMoney, (refundServiceFee).intValue(),
                DoubleUtil.parseDouble(Double.parseDouble(fee_amt) * 100).intValue());
        //下发退款查询消息
//        weixinPayService.sendPayMsg(refundNO, RechargeConstant.PAY_REFUND);
        Account account = accountService.getByAccountId(refundOrder.getAdAccountId());
        String refundBusinessNO = refundOrder.getBusinessNO();
        Integer operatorId = refundOrder.getOperatorId();
        String operatorName = refundOrder.getOperatorName();
        String operatorPhone = refundOrder.getOperatorPhone();
        String transactionLogRemark = refundOrder.getTransactionLogRemark();

        adaPayService.pushRefundDetailLog(user, account, feeMoney, refundNO, refundBusinessNO, recharge, operatorId, operatorName, operatorPhone, null, rideOrderNo, transactionLogRemark,time);


        List<UserAdaPayLog> userAdaPayLogsToRecord = userAdaPayLogService.getByPaymentId(adaPayLog.getAdaPayId());
        log.info("记录分账比例信息={}",JSON.toJSONString(userAdaPayLogsToRecord));
        UserAdaPayLog userAdaPayLog = userAdaPayLogsToRecord.get(0);
        for (DivMembers d : divMembers) {
            // 品牌
            Integer brandId = userAdaPayLog.getBrandId();
            // 区域
            Integer areaId = adaPayLog.getAccountId();
            // 用户编号
            String userNO = d.getMember_id();
            // 汇付平台支付订单号
            String adapayNO = adaPayLog.getAdaPayId();
            // 用户id
            Integer userId = adaPayLog.getUserId();
            // 业务平台支付订单号
            String rechargeNO = recharge.getOrderNO();
            // 退款请求号 refundNO

            // 本次退款金额
            double thisRefundMoney = DoubleUtil.parseDouble(Double.parseDouble(d.getAmount()) * 100).intValue();

            // 分账比例
            Optional<UserAdaPayLog> userAdaPayLogOptional = userAdaPayLogsToRecord.stream()
                    .filter(x -> Objects.equals(x.getUserNO(), userNO))
                    .findFirst();

            UserAdaPayLog userAdaPayLog1 = userAdaPayLogOptional.orElse(null);
            Double proportion = userAdaPayLog1 == null ? -1d : userAdaPayLog1.getProportion();

            // 退款手续费（三方支付系统收取）单位：分
            Integer refundFee = 0;
            if (d.getMember_id().equals(mainUserNO)) {
                refundFee = DoubleUtil.parseDouble(Double.parseDouble(fee_amt) * 100).intValue();
            }
            // 退款服务费（我们平台收取）单位：分
            Integer refundServiceFee1 = (refundServiceFee).intValue();
            // 退款时间  time
            // 操作人
            String name = refundOrder.getOperatorName();

            RefundAdapayRecord refundAdapayRecord =
                    new RefundAdapayRecord(brandId,areaId,userNO,adapayNO,userId,rechargeNO,refundNO,
                            refundMoney,thisRefundMoney,proportion,refundFee,refundServiceFee1,time.toString(),name);
            refundAdapayRecordDao.insert(refundAdapayRecord);
        }
    }

    private void apiLog1(DateTime time, String refundNO, Message message){
        log.info("参数refundNO={}",refundNO);
        RefundOrder refundOrder = refundOrderDao.getByRefundNO(refundNO);
        String buyOrderNO = refundOrder.getBusinessNO();
        RideLog rideLog = rideLogService.getByOrderNO(buyOrderNO);
        Integer adAccountId = refundOrder.getAdAccountId();
        Integer rechargeType = null;
        Integer userId = refundOrder.getUserId();
        User user = userService.getByUserId(userId);
        Integer operatorId = refundOrder.getOperatorId();
        String operatorPhone = refundOrder.getOperatorPhone();
        Double refundMoney = refundOrder.getAlreadyRefundMoney();
        // 订单总金额
        Double allMoney = refundOrder.getAllMoney();

//        // 计算骑行退款总额（罚款费用+骑行费用）
//        List<RefundOrder> refundOrderList = refundOrderDao.getByBusinessNO(refundBusinessNO);
//        Double allRefundMoney = 0d;
//        for (RefundOrder order : refundOrderList) {
//            allRefundMoney = allRefundMoney + order.getRefundMoney();
//        }

        /**如果是骑行订单*/
        if (rideLog != null) {
            RideRefundLog rideRefundLog = new RideRefundLog(adAccountId, rideLog.getOrderNO(), refundMoney.intValue(), time, user.getUserId(), user.getPhone(), operatorId, operatorPhone, rideLog.getOrderNO(), 1);
            rideRefundLogDao.insertLog(rideRefundLog);
        } else {
            Recharge rechargeDB = rechargeService.getByOrderNO(buyOrderNO);
            /**如果是卡券退款*/
            if (rechargeDB != null) {
                rechargeType = rechargeDB.getRechargeType();
                RefundOpeLog refundOpeLog = new RefundOpeLog(adAccountId, refundMoney.intValue(), time, userId, user.getPhone(), operatorId, operatorPhone, refundNO, rechargeType);
                log.info("插入退款操作记录refundOpeLog：" + refundOpeLog);
                refundOpeLogDao.insert(refundOpeLog);
                log.info("使卡券无效");
                invalidCard(rechargeDB);
            }
        }

        Integer sendMsg = refundOrder.getSendMsg();
        log.info("是否发送消息：{}", sendMsg);
        if (sendMsg != null && sendMsg == 1 && refundMoney > 0) {
            Account brand = accountDao.getByAdAccountId(adAccountId);
            SmsAuthConfig smsAuthConfig = smsAuthConfigDao.selectSmsConfig(brand.getParentId());
            String message1 = "你有一笔订单退款,订单金额为[" + allMoney / 100.0 + "],请前往小程序查看!";
            if (smsAuthConfig != null) {
                /**寻程发送短信*/
                ApiStoreMsgUtils.refundSend(user.getPhone(), message1, smsAuthConfig.getSmsCodeKey(), Integer.valueOf(smsAuthConfig.getModelId()));
            } else {
                Map<String, Integer> mapSMS = new HashMap<>();
                mapSMS.put("accountId", user.getAccountId());
                mapSMS.put("configType", 4);
                Account brandArea = accountDao.getByAccountId(user.getAccountId());
                BrandRemoteConfig brandRemoteConfig = smsAuthConfigDao.getByConfigType(mapSMS);
                if (brandRemoteConfig != null) {
                    String[] strings = brandRemoteConfig.getParamKV().split("&");
                    String accounts = strings[0].substring(strings[0].indexOf("=") + 1);
                    String password = strings[1].substring(strings[1].indexOf("=") + 1);
                    ClzySmsAuthUtil.sendSms(accounts, password, "【" + brandArea.getName() + "】" + message, user.getPhone());
                }
            }
            usermsgDao.add(new UserMsg(null, 0, user.getUserId(), time.toString(), null, 0, "骑行订单退款", message1, "", ""));
        }
    }

    private void apiLog2(String refundNO, DateTime time){
        log.info("参数refundNO={}",refundNO);
        RefundOrder refundOrder = refundOrderDao.getByRefundNO(refundNO);
        String buyOrderNO = refundOrder.getBusinessNO();
        // 通过buyOrderNO进行获取
        Recharge rechargeDB = rechargeService.getByOrderNO(buyOrderNO);
        Integer adAccountId = refundOrder.getAdAccountId();
        Account account = accountService.getByAccountId(adAccountId);
        Double refundMoney = refundOrder.getRefundMoney();
        Integer userId = refundOrder.getUserId();
        adaPayService.addRefundLog(rechargeDB, adAccountId, refundNO, refundMoney, userId, buyOrderNO);
        RideFeeLog rideFeeLog = new RideFeeLog();
        rideFeeLog.setOrderNO(buyOrderNO);
        // 总退款金额
        rideFeeLog.setRefundMoney(refundMoney.intValue());

        Double allAdaPayMoney = refundOrder.getAllAdaPayMoney();
        Double otherMoney = refundOrder.getOtherMoney();
        if (Objects.isNull(allAdaPayMoney) || Objects.isNull(otherMoney)){
            log.error("该数据不可能为空!!!");
            return;
        }
        rideFeeLog.setRefundRealMoney(allAdaPayMoney.intValue());
        rideFeeLog.setRefundOverMoney(otherMoney.intValue());
        // 分账退款金额
        rideFeeLogDao.editRefund(rideFeeLog);

        List<String> merchantNOList = Collections.singletonList(rechargeDB.getOrderNO());
        Integer changeType = refundOrder.getChangeType();
        String remark = refundOrder.getRemark();
        Integer operatorId = refundOrder.getOperatorId();
        String operatorName = refundOrder.getOperatorName();
        String operatorPhone = refundOrder.getOperatorPhone();
/*        if (remark != null) {
            remark = String.format(remark, new BigDecimal(refundMoney.toString()).divide(new BigDecimal(100)));
            remark = DateUtil.format(DateUtil.parse(callbackDataVo.getConfirmTime()), "yyyy-MM-dd HH:mm:ss") + remark;
        }*/
        User user = userService.getByUserId(userId);
        String rideOrderNo = refundOrder.getRideOrderNO();
        adaPayService.pushRefundLog(user, account, refundMoney, buyOrderNO, merchantNOList, rechargeDB,
                changeType, rideOrderNo, operatorId, operatorName, operatorPhone, remark,time);
//        /**使卡券失效*/
//        invalidCard(rechargeDB);
    }

    private void apiLog3(String refundNO,DateTime time){
        log.info("参数refundNO={}",refundNO);
        RefundOrder refundOrder = refundOrderDao.getByRefundNO(refundNO);
        log.info("获取到的refundorder信息{}",JSON.toJSONString(refundOrder));

        Integer userId = refundOrder.getUserId();
        User user = userService.getByUserId(userId);
        Integer adAccountId = refundOrder.getAdAccountId();
        Account account = accountService.getByAccountId(adAccountId);
        String buyOrderNO = refundOrder.getBusinessNO();
        Recharge rechargeDB = rechargeService.getByOrderNO(buyOrderNO);
        String rideOrderNo = refundOrder.getRideOrderNO();
        Integer operatorId = refundOrder.getOperatorId();
        String operatorName = refundOrder.getOperatorName();
        String operatorPhone = refundOrder.getOperatorPhone();
        /**添加退款记录*/
        RideFeeLog rideFeeLog = new RideFeeLog();
        rideFeeLog.setOrderNO(buyOrderNO);

/*        String businessNO = refundOrder.getBusinessNO();
        List<RefundOrder> refundOrderList = refundOrderDao.getByBusinessNO(businessNO);
        log.info("此次退款调用，进行退款的订单{}",JSON.toJSONString(refundOrderList));
        Double money = 0d;
        for (RefundOrder order : refundOrderList) {
            money = money + order.getRefundMoney();
        }*/

        Double refundMoney = Objects.isNull(refundOrder.getFineOrRideOrCardAllRefundMoney()) ? 0d : refundOrder.getFineOrRideOrCardAllRefundMoney();
        rideFeeLog.setRefundMoney(refundMoney.intValue());

        Double allAdaPayMoney = Objects.isNull(refundOrder.getFineOrRideOrCardAllAdapayRefundMoney()) ? 0d : refundOrder.getFineOrRideOrCardAllAdapayRefundMoney();
        Double otherMoney = Objects.isNull(refundOrder.getOtherMoney()) ? 0d : refundOrder.getOtherMoney();

        rideFeeLog.setRefundRealMoney(allAdaPayMoney.intValue());
        rideFeeLog.setRefundOverMoney(otherMoney.intValue());
        rideFeeLogDao.editRefund(rideFeeLog);

        String merchantNOListStr = refundOrder.getMerchantNOListStr();
        List<String> merchantNOList = JSON.parseArray(merchantNOListStr, String.class);

        Integer changeType = refundOrder.getChangeType();
        String remark = refundOrder.getRemark();


/*        if (remark != null) {
            remark = String.format(remark, new BigDecimal(money.toString()).divide(new BigDecimal(100)));
            remark = DateUtil.format(DateUtil.parse(callbackDataVo.getConfirmTime()), "yyyy-MM-dd HH:mm:ss") + remark;
        }*/

        log.info("推送RefundLog，参数user={}，account={}，refundMoney={}，buyOrderNO={},merchantNOList={}," +
                "rechargeDB={},changeType={},rideOrderNo={},operatorId={},operatorName={},operatorPhone={},remark={},time={}",
                JSON.toJSONString(user),JSON.toJSONString(account),refundMoney,buyOrderNO,JSON.toJSONString(merchantNOListStr),
                JSON.toJSONString(rechargeDB),changeType,rideOrderNo,operatorId,operatorName,operatorPhone,remark,time);
        adaPayService.pushRefundLog(user, account, refundMoney, buyOrderNO, merchantNOList, rechargeDB,
                changeType, rideOrderNo, operatorId, operatorName, operatorPhone, remark, time);
    }

    private void apiLog4(String refundNO){
        log.info("参数refundNO={}",refundNO);
        RefundOrder refundOrder = refundOrderDao.getByRefundNO(refundNO);
        Recharge recharge = rechargeService.getByOrderNO(refundOrder.getRechargeNO());
        Integer adAccountId = refundOrder.getAdAccountId();
        Double realRefundMoney = refundOrder.getRefundMoney();
        Integer userId = refundOrder.getUserId();
        String buyOrderNO = refundOrder.getBusinessNO();

        log.info("添加addRefundLog，参数recharge={},adAccountId={},refundNO={},realRefundMoney={},userId={},buyOrderNO={}"
                ,JSON.toJSONString(recharge),adAccountId,refundNO,realRefundMoney,userId,buyOrderNO);

        adaPayService.addRefundLog(recharge, adAccountId, refundNO, realRefundMoney, userId, buyOrderNO);
    }

    /**
     * 卡券失效
     *
     * @param recharge
     */
    private void invalidCard(Recharge recharge) {
        Integer rechargeType = recharge.getRechargeType();
        String orderNO = recharge.getOrderNO();
        Integer userId = recharge.getUserId();
        if (rechargeType == null) {
            return;
        }
        if (rechargeType.equals(RechargeConstant.recharge_Mem)) {
            log.info("============免押卡退款========");
            Map<String, Object> map = memberFeeDao.selectByOrderNO(orderNO);
            Integer accountId = (Integer) map.get("accountId");
            Integer type = (Integer) map.get("type");
            int count = memberFeeDao.countValid(accountId, userId);
            count = count == 1 ? 1 : 0;
            //修改该订单卡到期时间为今天过期
            int i = memberFeeDao.updateExpireTime(orderNO);
            /*修改用户区域免押到期时间*/
            agentDepositVipDao.updateExpire(accountId, userId, type);
            /*兼容免押卡多出购买的时间*/
            if (count == 1) {
                agentDepositVipDao.updateExpire(accountId, userId, 0);
            } else {
                //兼容购买多张免押卡，卡上到期时间正确
                memberFeeDao.updateExpireTimes((String) map.get("expireTime"), accountId, userId, type);
            }

        }
        //骑行卡退款
        if (rechargeType.equals(RechargeConstant.recharge_rideCard)) {
            log.info("============骑行卡退款========");
            UserMember userMember = new UserMember(orderNO);
            int i = rideCardDao.updateValid(userMember);

        }
        //会员卡退款
        if (rechargeType.equals(RechargeConstant.recharge_vip)) {
            log.info("============会员卡退款========");
            int i = vipCardDao.updateValid(orderNO);
        }
        /**优惠券套餐退款*/
        if (rechargeType.equals(RechargeConstant.recharge_meal)) {
            log.info("============优惠券套餐退款========");
            UserMealLog userMealLog = userMealLogDao.getByOrderNO(recharge.getOrderNO());
            if (userMealLog == null) {
                return;
            }
            CouponMeal couponMeal = couponMealDao.getByMealId(userMealLog.getMealId());
            if (couponMeal == null) {
                return;
            }
            couponDao.userCouponEdit(couponMeal.getCouponId(), userId, recharge.getOrderNO());
        }
    }

    private void addRideUseLog(String orderNO, Recharge recharge, Double refundMoney, String partner,String time) {
        RideUseLog rideUseLog = rideUseLogService.getByOrderNO(orderNO);
        if (null != rideUseLog) {
            RideUseRefundLog rideUseRefundLog = new RideUseRefundLog();
            rideUseRefundLog.setAccountId(recharge.getBrandId());
            rideUseRefundLog.setAdAccountId(recharge.getAdAccountId());
            rideUseRefundLog.setOrderNO(rideUseLog.getOrderNO());
            rideUseRefundLog.setAddTime(DateUtil.parse(time));
            rideUseRefundLog.setRechargeOrderNO(recharge.getOrderNO());
            rideUseRefundLog.setPartner(partner);
            switch (recharge.getRechargeType()) {
                case 3:
                    /**充值结束订单**/
                    Double otherRefund = rideUseLog.getOtherRefund() + refundMoney;
                    log.info("充值订单号=" + recharge.getOrderNO() + ",骑行订单号=" + rideUseLog.getOrderNO() + ",3更新其他退款=" + otherRefund);
                    rideUseLog.setOtherRefund(otherRefund.intValue());//其他退款
                    rideUseLogService.update(rideUseLog);
                    rideUseRefundLog.setBalanceRefund(0);
                    rideUseRefundLog.setOtherRefund(refundMoney.intValue());
                    rideUseRefundLogDao.insert(rideUseRefundLog);
                    break;
                case 0:
                    /**押金和充值**/
                    Double balanceRefund = rideUseLog.getBalanceRefund() + refundMoney;
                    log.info("充值订单号=" + recharge.getOrderNO() + ",骑行订单号=" + rideUseLog.getOrderNO() + ",1更新余额退款=" + balanceRefund);
                    rideUseLog.setBalanceRefund(balanceRefund.intValue());//余额退款
                    rideUseLogService.update(rideUseLog);
                    rideUseRefundLog.setBalanceRefund(refundMoney.intValue());
                    rideUseRefundLog.setOtherRefund(0);
                    rideUseRefundLogDao.insert(rideUseRefundLog);
                    break;
                default:
            }
        }
    }


}
